import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

var URL = 'localhost:8092'
var baseURL = 'http://' + URL + '/'
export {
  URL,
  baseURL
}

// create an axios instance
const service = axios.create({
  baseURL: baseURL + 'admin/',
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['__TOKEN__'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    return res
  },
  error => {
    if (error.response.status === 401) {
      Message({
        message: error.response.data.msg,
        type: 'error',
        duration: 5 * 1000
      })
      setTimeout(function() {
        store.dispatch('user/resetToken').then(() => {
          location.reload()
        })
      }, 500)
      return Promise.reject(error.response)
    } else {
      Message({
        message: error.response.data.msg,
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(error.response)
    }
  }
)

export default service
